<template>
    <el-row :gutter="20">
        <el-col :span="24" class="mt mb">
            <el-select class="w200" size="small" @change="selGuest" v-model="ginfo.name" filterable remote reserve-keyword placeholder="客户姓名 / 电话 / 卡号" :remote-method="queryGuest" :loading="loading">
                <el-option v-for="(g, k) in glist" :value="Object.assign({}, g)" :key="k">
                    {{g.name}} -- {{g.vipcard}}
                </el-option>
            </el-select>
            <el-tag class="ml" v-show="ginfo.id">{{ginfo.sex?'男':'女'}}</el-tag>
            <el-tag class="ml" v-show="ginfo.id">电话：{{ginfo.phone}}</el-tag>
            <el-tag class="ml" v-show="ginfo.id">卡号：{{ginfo.vipcard}}</el-tag>
            <el-tag v-show="ginfo.id" class="ml">账户余额：{{ginfo.balance}} 元</el-tag>
            <el-tag v-show="ginfo.id" class="ml">赠送余额：{{ginfo.giftbalance}} 元</el-tag>
        </el-col>
        <el-col :span="24" class="mb">
            <el-alert title="左侧为客户需要退的期卡或疗程卡，右侧则为退的卡有使用记录。下方退款提示仅为建议不做具体退款金额。" type="info" :closable="false">
            </el-alert>
        </el-col>
        <el-col :span="13">
            <div class="block">
                <el-tag type="warning" size="medium" class="w200 center">需要退的卡项</el-tag>
                <el-button type="primary" icon="el-icon-h-tuika1" size="mini" class="fr" @click="delectCards">选择卡项</el-button>
            </div>
            <el-table :data="delcards" :stripe="true" empty-text="客户需要退订的卡" height="300">
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="name" label="卡项"></el-table-column>
                <el-table-column prop="type" label="类型">
                    <template slot-scope="scope">
                        <el-tag size="mini" type="success" v-if="scope.row.type==1">期卡</el-tag>
                        <el-tag size="mini" type="info" v-else>疗程</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="disprice" label="折后价">
                    <template slot-scope="scope">
                        <span v-if="scope.row.disprice">{{scope.row.disprice+'元'}}</span>
                        <span v-else>0 元</span>
                    </template>
                </el-table-column>
                <el-table-column label="总数">
                    <template slot-scope="scope">
                        <span v-if="scope.row.num != null">{{scope.row.num}}次</span>
                    </template>
                </el-table-column>
                <el-table-column label="剩余数">
                    <template slot-scope="scope">
                        <span v-if="scope.row.nownum != null">{{scope.row.nownum}}次</span>
                    </template>
                </el-table-column>
                <el-table-column label="有效期" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span v-if="scope.row.endtime != null">{{times(scope.row.endtime)}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="购卡来源">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-h-chakan" size="mini" @click="look(scope.row.orderid)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-tag class="mt mb">
                {{advice.gkze}} - {{advice.xfze}} - {{advice.zsze}} = {{advice.all}} (元)
            </el-tag>
            <el-alert title="以上为退疗程卡所建议的退款金额（非必需），期卡需要根据店家情况自行退款！" type="error" :closable="false">
            </el-alert>
        </el-col>
        <el-col :span="11">
            <el-tag type="warning" size="medium" class="w200 center">已消费赠送的品项</el-tag>
            <el-table :data="rdsinfo" :stripe="true" height="300">
                <el-table-column prop="name" label="名称">
                    <template slot-scope="scope">
                        <span v-if="scope.row.name">{{scope.row.name}}</span>
                        <span v-else>无卡名</span>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="类型">
                    <template slot-scope="scope">
                        <el-tag type="info" size="mini" v-if="scope.row.type==1">产品</el-tag>
                        <el-tag size="mini" v-else>项目</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="price" label="标准价">
                    <template slot-scope="scope">{{scope.row.price+'元'}}</template>
                </el-table-column>
                <el-table-column prop="usenum" label="使用数量"></el-table-column>
            </el-table>
            <div class="block mt mb ov">
                <el-input size="small" placeholder="请输入退款金额！" v-model="backmoney" class="w300 fl">
                    <template slot="prepend">退款金额</template>
                </el-input>
                <el-checkbox v-model="store" class="fr" style="line-height: 32px;">存入余额</el-checkbox>
            </div>
            <el-input type="textarea" placeholder="请输入退卡描述" v-model="remarks"></el-input>
            <div class="block right mt">
                <el-button type="success" icon="el-icon-upload" @click="submit">确定退卡</el-button>
                <el-button type="danger" icon="el-icon-close" @click="close">取消关闭</el-button>
            </div>
        </el-col>
    </el-row>
</template>
<script>
import C from '@/common/common.js'
import P from '@/service/shop/popup.js'
export default {
  name: 'backCard',
  data () {
    return {
      ginfo: {},
      delcards: [], // 需要退的卡
      rdsinfo: [], // 当前退的卡所消耗的品项
      backmoney: '', // 退款金额
      remarks: '', // 退卡描述
      store: false,
      advice: {
        gkze: 0, // 购卡总额
        xfze: 0, // 卡消费总额
        zsze: 0, // 赠送品项消费金额
        all: 0
      },
      glist: [],
      timeout: null,
      loading: false
    }
  },
  methods: {
    queryGuest: function (query) {
      if (query !== '') {
        this.loading = true
        clearTimeout(this.timeout)

        this.timeout = setTimeout(async () => {
          let res = await C.ajax('/shop/backcard/queryguests', { query: query })
          if (res) {
            this.loading = false
            this.glist = res
          }
        }, 300)
      } else {
        this.glist = []
      }
    },

    selGuest: function (row) {
      this.ginfo = row
    },

    delectCards: async function () {
      if (!this.ginfo.id) {
        C.error('请选择需要退卡的顾客')
        return false
      }
      this.advice.gkze = 0
      this.advice.xfze = 0
      this.rdsinfo = []
      this.delcards = []
      let res = await C.openBrowserWindow('/selectGuestCard', { gid: this.ginfo.id }, { width: 1300, height: 700, useSpa: false, spaModel: 'shop', transparent: true, frame: false })

      if (res) {
        let rlist = [],
          oids = []
        let jsA = 0,
          jsR = 0
        res.rcs.forEach((v) => {
          rlist.push({
            id: v.id,
            orderid: v.orderid,
            price: v.price,
            disprice: v.disprice,
            name: v.name,
            type: 2,
            num: v.num,
            nownum: v.nownum
          })
          if (oids.indexOf(v.orderid) === -1) {
            oids.push(v.orderid)
          }
          jsA += v.disprice * v.num
          jsR += v.price * (v.num - v.nownum)
        })

        res.rqs.forEach((v) => {
          rlist.push({
            id: v.id,
            cardid: v.cardid,
            orderid: v.orderid,
            name: v.name,
            disprice: v.price,
            type: 1,
            endtime: v.endtime
          })
          if (oids.indexOf(v.orderid) === -1) {
            oids.push(v.orderid)
          }
          this.advice.gkze += v.price
        })

        this.advice.gkze = jsA.toFixed(2)
        this.advice.xfze = jsR.toFixed(2)

        this.delcards = rlist
        this.reduceLog(oids)
      }
    },

    reduceLog: async function (oids) {
      let res = await C.ajax('/shop/backcard/getreducelog', { oid: JSON.stringify(oids) }, 'post')
      if (res) {
        let usesubs = []
        let zsje = 0
        res.rsubs.forEach((v) => {
          if (v.num - v.nownum > 0) {
            v.usenum = v.num - v.nownum
            v.type = 2
            zsje += v.price * v.usenum
            usesubs.push(v)
          }
        })
        res.rgods.forEach((v) => {
          if (v.num - v.nownum > 0) {
            v.usenum = v.num - v.nownum
            zsje += v.price * v.usenum
            v.type = 1
            usesubs.push(v)
          }
        })
        this.advice.zsze = zsje.toFixed(2)
        this.advice.all = (this.advice.gkze - this.advice.xfze - this.advice.zsze).toFixed(2)
        this.rdsinfo = usesubs
      }
    },

    submit: function () {
      let that = this

      if (!that.ginfo.id) {
        C.error('请选择需要退卡的顾客！')
        return false
      } else if (!that.delcards.length) {
        C.error('请选择需要退的卡项！')
        return false
      } else if (!/^\d+(\.\d+)?$/.test(that.backmoney)) {
        C.error('退款金额不正确！')
        return false
      }

      // 聚合期卡id，疗程卡id（用于停用客户卡项表项目）
      // 聚合期卡和疗程卡订单id（用于停用客户仓库里赠送的产品）
      let qkid = [],
        oids = [],
        lcid = []
      for (var i = 0, delcardslen = that.delcards.length; i < delcardslen; i++) {
        if (that.delcards[i].type === 1) {
          if (oids.indexOf(that.delcards[i].orderid) === -1) {
            oids.push(that.delcards[i].orderid)
          }
          qkid.push(that.delcards[i].cardid)
        } else {
          if (oids.indexOf(that.delcards[i].orderid) === -1) {
            oids.push(that.delcards[i].orderid)
          }
          lcid.push(that.delcards[i].id)
        }
      }

      let data = {
        ginfo: that.ginfo,
        oids: oids,
        qkid: qkid,
        lcid: lcid,
        store: this.store,
        backmoney: that.backmoney,
        remarks: that.remarks
      }

      C.confirm('确定退卡吗？', async () => {
        let res = await C.ajax('/shop/backcard/backcards', { data: JSON.stringify(data) }, 'post')
        if (res) {
          C.closeBrowserWindow(res)
        }
      })
    },

    async look (id) {
      let res = await P.openCardPopup({ id: id })
      if (res) C.success(res.data.info)
    },

    times: function (unix) {
      return C.time(unix)
    },
    close () {
      C.closewin()
    }
  }
}
</script>
<style>
.ov {
    overflow: hidden;
}

.ov-x {
    overflow-x: hidden;
}

.fl {
    float: left;
}

.fr {
    float: right;
}

.clear {
    clear: both;
}

.none {
    display: none;
}

.block {
    display: block;
}

.handel {
    cursor: pointer;
}





/*背景颜色-前景颜色*/

.bg-dark {
    background: #F9FAFC;
}

.bg-extra {
    background: #EFF2F7;
}

.bg-light {
    background: #E5E9F2;
}

.bg-gray {
    background: #D3DCE6;
}

.bg-silver {
    background: #8492A6;
}

.bg-black {
    background: #324057;
}

.white {
    color: white;
}

.black {
    color: #324057;
}

.green {
    color: green;
}

.blue {
    color: blue;
}

.red {
    color: red;
}

.color-nan {
    color: #2a91f7;
}

.color-nv {
    color: #f7992a;
}





/*其他样式*/

html {
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
    font-weight: 400;
}

.title {
    font-size: 16px;
    font-family: "Helvetica Neue", "Helvetica", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    line-height: 26px;
    margin: 10px 0;
}

.border {
    border: 1px solid #dfe6ec;
    border-radius: 4px;
    padding: 0 8px;
}

.bd {
    border: 1px solid #dfe6ec;
}

.border-b {
    border-bottom: 1px solid #dfe6ec;
}

.border-t {
    border-top: 1px solid #dfe6ec;
}

.bd-l {
    border-left: 1px dashed #dfe6ec;
}

.bd-t {
    border-top: 1px dashed #dfe6ec;
}

.bd-r {
    border-radius: 50%;
}

.underline {
    text-decoration: underline;
}





/*边距*/

.p0 {
    padding: 0 !important;
}

.m0 {
    margin: 0 !important;
}

.m10 {
    margin: 10px !important;
}

.m15 {
    margin: 15px !important;
}

.p10 {
    padding: 10px !important;
}

.p15 {
    padding: 15px !important;
}

.ml {
    margin-left: 15px !important;
}

.mr {
    margin-right: 15px !important;
}

.mb {
    margin-bottom: 15px !important;
}

.mt {
    margin-top: 15px !important;
}

.pl {
    padding-left: 15px !important;
}

.pl0 {
    padding-left: 0 !important;
}

.pr {
    padding-right: 15px !important;
}

.pr0 {
    padding-right: 0 !important;
}

.pb {
    padding-bottom: 15px !important;
}

.pt {
    padding-top: 15px !important;
}

.center {
    text-align: center !important;
}

.left {
    text-align: left !important;
}

.right {
    text-align: right !important;
}

.w100 {
    width: 100px !important;
}

.w150 {
    width: 150px !important;
}

.w200 {
    width: 200px !important;
}

.w300 {
    width: 300px !important;
}

.w400 {
    width: 400px !important;
}

.w500 {
    width: 500px !important;
}

.w30 {
    width: 30%;
}

.w50 {
    width: 50%;
}

.width95 {
    width: 95%;
}

.width {
    width: 100% !important;
}

.h200 {
    height: 200px;
}

.h300 {
    height: 300px;
}

.h500 {
    height: 500px;
}

.h600 {
    height: 600px;
}

.h700 {
    height: 700px;
}

.h800 {
    height: 800px;
}

.l28 {
    line-height: 28px;
}

.l30 {
    line-height: 30px;
}

.l50 {
    line-height: 50px;
}





/*附加订制样式*/

.el-row {
    margin: 0 !important;
}

.el-table .cell {
    padding: 0;
    text-align: center;
}

.el-textarea__inner {
    resize: none;
}

.el-input.is-disabled .el-input__inner {
    color: #20A0FF;
}

.el-textarea.is-disabled .el-textarea__inner {
    color: #444;
}

.el-switch {
    line-height: 0;
}

.el-checkbox+.el-checkbox {
    margin-left: 0;
}

.el-checkbox {
    margin-right: 20px;
}

.el-autocomplete-suggestion li {
    padding: 4px 20px;
    line-height: 20px;
}

.el-table th {
    padding: 10px 0;
}

.el-table td {
    padding: 4px 0;
}
</style>